package com.andeveloper.springdemo.service.impl.user;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.andeveloper.springdemo.dao.UserDao;
import com.andeveloper.springdemo.model.User;
import com.andeveloper.springdemo.service.user.UserService;
@Service
public class UserServiceImpl implements UserService {
	private static Logger logger = Logger.getLogger(UserServiceImpl.class);

	@Resource
	private UserDao userDao;
	@Override
	public User findUserByName(String userName) {
		return userDao.findUserByName(userName);
	}
	@Override
	public User register(User user) {
		String algorithmName = "md5";
		String source = user.getPassword();
		SecureRandomNumberGenerator numberGenerator = new SecureRandomNumberGenerator();
		String userName = user.getUserName();
		String salt = userName + numberGenerator.nextBytes().toHex();
		int hashIterations = 2;
		SimpleHash hash = new SimpleHash(algorithmName, source, salt, hashIterations);
		user.setPassword(hash.toHex());
		user.setSalt(salt);
		Integer result = userDao.addUser(user);
		if(result > 0) {
			return userDao.findUserByName(userName);
		}
		return null;
	}
}
